package com.thrd.basicframework.ui.recyclerview;

import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.RecyclerView;

import com.thrd.basicframework.R;


/**
 * @author: ${唐杰}
 * @date: 2021/3/24
 */
public class MaxHeightRecyclerView extends RecyclerView {

    private float mMaxHeight;

    /**
     * 设置最大高度
     *
     * @param maxHeight 最大高度 px
     */
    public void setMaxHeight(float maxHeight) {
        this.mMaxHeight = maxHeight;
        // 重绘 RecyclerView
        requestLayout();
    }


    public MaxHeightRecyclerView(@NonNull Context context) {
        this(context,null);
    }

    public MaxHeightRecyclerView(@NonNull Context context, @Nullable AttributeSet attrs) {
        this(context, attrs,0);
    }

    public MaxHeightRecyclerView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.MaxHeightRecyclerView, defStyleAttr,0);
        mMaxHeight= a.getDimension(R.styleable.MaxHeightRecyclerView_maxHeight,100);
        a.recycle();
    }


    @Override
    protected void onMeasure(int widthSpec, int heightSpec) {

//        int heightMode = MeasureSpec.getMode(heightSpec);
//        int heightSize = MeasureSpec.getSize(heightSpec);
//        getDefaultSize(heightSize,)
//
//        // Height
//        if (heightMode == MeasureSpec.EXACTLY) {
//            height = heightSize;
//        } else if (heightMode == MeasureSpec.AT_MOST) {
//            height = Math.min(desiredHeight, heightSize);
//        } else {
//            height = desiredHeight;
//        }


        if (mMaxHeight > 0) {
            heightSpec = View.MeasureSpec.makeMeasureSpec((int) mMaxHeight, View.MeasureSpec.AT_MOST);
        }
        super.onMeasure(widthSpec, heightSpec);
    }



    public static int getDefaultSize(int size, int measureSpec) {
        int result = size;
        int specMode = MeasureSpec.getMode(measureSpec);
        int specSize = MeasureSpec.getSize(measureSpec);

        switch (specMode) {
            case MeasureSpec.UNSPECIFIED:
                result = size;
                break;
            case MeasureSpec.AT_MOST:
            case MeasureSpec.EXACTLY:
                result = specSize;
                break;
        }
        return result;
    }


}
